package com.shigen.file.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shigen.file.entity.BaseUserFile;
import com.shigen.file.entity.UserInfo;
import com.shigen.file.mapper.BaseUserFileMapper;
import com.shigen.file.service.IBaseUserFileService;
import com.shigen.file.service.IUserInfoService;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户文件表 服务实现类
 * </p>
 *
 * @author shigen.fu
 * @since 2022-06-04
 */
@Service
public class BaseUserFileServiceImpl extends ServiceImpl<BaseUserFileMapper, BaseUserFile> implements IBaseUserFileService {

  private static final String ROOT_FILE_ID = "0";

  @Resource
  private IUserInfoService userInfoService;

  @Override
  public List<BaseUserFile> getUserFileTree() {
    // 查出当前用户的所有文件
    UserInfo curUserInfo = userInfoService.getCurUserInfo();
    Integer userId = curUserInfo.getUserId();
    List<BaseUserFile> baseUserFiles = getBaseMapper()
        .selectList(lambdaQuery().eq(userId != null, BaseUserFile::getUploadUserId, userId)
            .eq(BaseUserFile::getIsDel, 0).orderByDesc(BaseUserFile::getCreateTime).getWrapper());

    // 获得所有的一级文件
    baseUserFiles.stream().filter(baseUserFile -> baseUserFile.getParentId().equals(ROOT_FILE_ID))
        .map((baseUserFile -> {
          baseUserFile.setChildren(getChildren(baseUserFile, baseUserFiles));
          return baseUserFile;
        })).collect(Collectors.toList());

    return baseUserFiles;
  }

  /**
   * 递归获得文件下的文件
   */
  private List<BaseUserFile> getChildren(BaseUserFile root, List<BaseUserFile> files) {
    return files.stream().filter(file -> file.getParentId().equals(root.getUnionId()))
        .map(file -> {
          file.setChildren(getChildren(file, files));
          return file;
        })
        .collect(Collectors.toList());
  }
}
